package com.bai.ad.service.impl;

import com.bai.ad.constant.Constants;
import com.bai.ad.dao.AdUserRepository;
import com.bai.ad.entity.AdUser;
import com.bai.ad.service.IUserService;
import com.bai.ad.util.CommonUtils;
import com.bai.ad.vo.CreateUserRequest;
import com.bai.ad.vo.CreateUserResponse;
import com.bao.ad.exception.AdException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * ClassName IUserServiceImpl
 *
 * @author Bai
 * @version 1.0
 * @date 2019/2/19 0019 下午 22:11
 **/
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    private final AdUserRepository adUserRepository;

    public UserServiceImpl(AdUserRepository adUserRepository) {
        this.adUserRepository = adUserRepository;
    }

    /**
     * <h2>创建用户</h2>
     *
     * @param request 请求
     * @return CreateUserResponse
     * @throws AdException 统一错误
     */
    @Override
    @Transactional
    public CreateUserResponse createUser(CreateUserRequest request) throws AdException {

        if(!request.validate()){
            throw  new AdException(Constants.ErrorMsg.REQUEST_PARAM_ERROR);
        }

        AdUser byUsername = adUserRepository.findByUsername(request.getUsername());
        if(null != byUsername){
            throw new AdException(Constants.ErrorMsg.SAME_NAME_ERROR);
        }

        AdUser adUser = adUserRepository.save(new AdUser(
                request.getUsername(), CommonUtils.md5(request.getUsername())
        ));

        return new CreateUserResponse(adUser.getId(), adUser.getUsername(),
                adUser.getToken(), adUser.getCreateTime(), adUser.getUpdateTime());

    }
}
